package com.none.web.service.user.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;








import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.MD5Util;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.model.Pager;
import com.none.core.service.BaseServiceSupport;
import com.none.web.QRcode.coder.NewUserSignUpQRCoder;
import com.none.web.QRcode.constants.AppConstants;
import com.none.web.common.SysConstant;
import com.none.web.model.TCodes;
import com.none.web.model.TStaffpushinfo;
import com.none.web.model.TUser;
import com.none.web.model.TUserApp;
import com.none.web.service.user.IUserService;

/**
 * 用户管理Service实现
 * 
 * @author Summer
 * 
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceSupport implements IUserService {
	@Autowired
	private HttpServletRequest request;
	@Autowired
    JdbcTemplate jdbcTemplate;
	
	/*
	 * 密码验证 正则表达式
	 */
	//private static String PASSWORD_REGEX = "^(?=.*\\d)(?=.*([a-z]|[A-Z]))(?=.*[`~!@#$%^&*(){}\\[\\]|\\\\;:'\",<.>/\\?]).{8,15}$";
	private static String PASSWORD_REGEX = "^(?=.*\\d)(?=.*([a-z]|[A-Z])).{8,15}$";
	private static String USERNAME_REGEX = "^.{4,15}$";

	@Override
	public Object addUser(TUserApp user) throws Exception {
		if (StringUtils.isBlank(user.getUserName()))
			throw new ValidateException("user.userNameNull");

		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userName", user.getUserName()));
		List<?> userList = userCriteria.list();
		if (userList.size() > 0) {
			throw new ValidateException("user.userNameIsExist");
		}
		// 用户号
		String userId = CreateID.getID();
		// 激活码号
		String codeId = CreateID.getID();

		user.setUserId(userId);
		// 默认不可用
		user.setState(SysConstant.STATE_NOT_AVAILABLE);

		// 激活码信息
		TCodes code = new TCodes();
		code.setCodeId(codeId);
		// 激活码位数为8位
		code.setCode(UUID.randomUUID().toString().replaceAll("-", "").toLowerCase().substring(0, 8));
		// 创建时间
		code.setCreateTime(new Timestamp(new Date().getTime()));
		// 默认激活码可用
		code.setState(SysConstant.STATE_AVAILABLE);

		saveEntity(code);
		// 设置用户的时间
		user.setCreateTime(new Timestamp(new Date().getTime()));

		user.setLastTime(new Timestamp(new Date().getTime()));

		user.setLoginTime(new Timestamp(new Date().getTime()));

		user.setTcodes(code);

		// 保存用户信息
		if (saveEntity(user) == null) {
			throw new ValidateException("common.sysException");
		}
		return user;
	}

	@Override
	public Object editUser(TUser user) throws Exception {
		
		TUser tUser = null;
		if (user != null && StringUtils.isNotBlank(user.getUserId())) {
			tUser = findEntity(TUser.class, user.getUserId());
			if (tUser != null) {
				user.setLastTime(new Timestamp(new Date().getTime()));
				updateEntity(user);
				tUser = findEntity(TUser.class, user.getUserId());
			}
		}
		if (tUser != null) {
			return tUser;
		} else {
			throw new ValidateException("user.userUnExist");
		}
	}

	@Override
	public boolean delUser(String id) throws Exception {
		TUser tUser = null;
		if (StringUtils.isNotBlank(id)) {
			tUser = findEntity(TUser.class, id);
			if (tUser != null) {
				deleteEntity(tUser);
				return true;
			} else {
				throw new ValidateException("user.userUnExist");
			}
		}
		return false;
	}

	@Override
	public Object listUser(Pager pager, String keyWord, String code, String status) {
		Criteria criteria = getCriteria(TUser.class);
		criteria.add(Restrictions.or(Restrictions.eq("role", ""), Restrictions.isNull("role")));
		if (StringUtils.isNotBlank(keyWord)) {
			criteria.add(Restrictions.or(Restrictions.like("userName", "%" + keyWord + "%"),Restrictions.eq("userId", keyWord)));
		}
		if (StringUtils.isNotBlank(code)) {
			criteria.createAlias("tcodes", "tc");
			criteria.add(Restrictions.eq("tc.code", code));
		}
		if (StringUtils.isNotBlank(status)) {
			criteria.add(Restrictions.eq("state", Integer.parseInt(status)));
		}
		criteria.addOrder(Order.desc("createTime"));
		return listPageQBCL(criteria, pager);
	}

	@Override
	public TUserApp mergeActiveUser(String userName, String password, String code, String udid) throws Exception {
		
		// 密码8位，并且带有字母数字和特殊符号
		if (!StringUtil.regex(password, PASSWORD_REGEX))
			throw new ValidateException("user.passwordAlert");
		if (StringUtils.isBlank(udid)) {
			throw new ValidateException("user.udidisnull");
		}
		TUserApp user = null;
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userName", userName));
		List<?> userList = userCriteria.list();
		if (!userList.isEmpty()) {
			if (userList.size() == 1) {
				TUserApp tUser = (TUserApp) userList.get(0);
				if (tUser.getState() == SysConstant.STATE_NOT_AVAILABLE) {
					TCodes nowCode = tUser.getTcodes();
					// 有效的激活码
					if (nowCode != null) {
						if (nowCode.getState() == SysConstant.STATE_AVAILABLE) {
							//输入的激活码和服务端的是否一致
                            if(!code.equals(nowCode.getCode())){
                            	throw new ValidateException("user.codeInvalid");
                            }							
							//激活码时间是否已经过期了
							long codeTimeDay = (new Date().getTime() - nowCode.getEnableTime().getTime())
									/ (1000 * 60 * 60 * 24);
							if (codeTimeDay <= 10) {
								user = tUser;
								// 设置用户密码
								user.setPassword(MD5Util.getMD5String(password).toLowerCase());
								// 设置用户状态为可用
								user.setState(SysConstant.STATE_AVAILABLE);
								// 设置用户的udid值
								user.setUserUDID(udid);
								// 更新用户信息
								updateEntity(user);
								// 设置激活码的状态为不可用
								nowCode.setState(SysConstant.STATE_NOT_AVAILABLE);
								// 更新激活码信息
								updateEntity(nowCode);
							} else {
								throw new ValidateException("user.codeExpired");
							}
						} else {
							throw new ValidateException("user.codeInvalidUsed");
						}
					} else {
						throw new ValidateException("user.codeInvalid");
					}
				} else {
					throw new ValidateException("user.codeNoNeedActive");
				}
			} else {
				throw new ValidateException("common.illegalRequest");
			}
		} else {
			throw new ValidateException("user.userUnExist");
		}
		return user;
	}

	@Override
	public TUserApp mergeLoginUser(String userName, String password, String udid) throws Exception {
		if (StringUtils.isBlank(udid)) {
			throw new ValidateException("user.udidisnull");
		}
		TUserApp user = null;
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userName", userName));
		List<?> userList = userCriteria.list();
		if (!userList.isEmpty()) {
			if (userList.size() == 1) {
				TUserApp tUser = (TUserApp) userList.get(0);
				if (StringUtils.isNotBlank(tUser.getRole())) { // 如果用户存在角色的话，返回null
					return null;
				}
				//william hard code . add ingore udid
				if (udid.equals(tUser.getUserUDID())||"ingore".equals(tUser.getUserUDID())) {
					if (password.equals(tUser.getPassword())) {
						if (tUser.getState() == SysConstant.STATE_AVAILABLE) {
							//save
							tUser.setLoginTime(new Timestamp(new Date().getTime()));
							/*if("ingore".equals(tUser.getUserUDID())){
								tUser.setUserUDID(udid);
							}*/
							/***** 保存用户信息  ****/
							if (saveEntity(tUser) == null) {
									throw new ValidateException("common.sysException");
							}
							// add by bing 2015-10-08   修改用户对应的云推送信息
							TStaffpushinfo push = this.findEntity(TStaffpushinfo.class, udid);
							if(push!=null){
								String sqlupdate = "update t_staff_push_info t set t.username='"+userName+"' where t.udid = '"+udid+"'";
								jdbcTemplate.execute(sqlupdate);
								//删除以前的旧的信息
								String sql = "delete from t_staff_push_info where username='"+userName+"' and addtime<'"+push.getAddtime()+"'";
								jdbcTemplate.execute(sql);
							}
							
							//
							user = tUser;
							
						} else {
							throw new ValidateException("user.needActive");
						}
					} else {
						throw new ValidateException("user.passwdNotRight");
					}
				} else {
					throw new ValidateException("user.udidNotIdentical");
				}
			} else {
				throw new ValidateException("common.illegalRequest");
			}
		} else {
			throw new ValidateException("user.userUnExist");
		}
		return user;

	}

	@Override
	public TUser mergeResetUser(String userName) throws Exception {
		TUser user = null;
		Criteria userCriteria = getCriteria(TUser.class);
		userCriteria.add(Restrictions.eq("userName", userName));
		List<?> userList = userCriteria.list();
		if (!userList.isEmpty()) {
			if (userList.size() == 1) {
				user = (TUser) userList.get(0);
				// 设置用户状态为不可用
				user.setState(SysConstant.STATE_NOT_AVAILABLE);
				// 生成新的激活码信息

				//TCodes code = findEntity(TCodes.class, user.getTcodes());
				// 激活码位数为8位
				//code.setCode(UUID.randomUUID().toString().replaceAll("-", "").toLowerCase().substring(0, 8));
				// 创建时间
				//code.setCreateTime(new Timestamp(new Date().getTime()));
				// 默认激活码可用
				//code.setState(SysConstant.STATE_AVAILABLE);

				//saveEntity(code);
				// 将新的激活码和用户进行关联
				//user.setTcodes(code);
				// 更新用户信息
				updateEntity(user);
			} else {
				throw new ValidateException("common.illegalRequest");
			}
		} else {
			throw new ValidateException("user.userUnExist");
		}
		return user;
	}

	@Override
	public TUserApp resetUserPassword(String userName, String oldPassword, String password) throws Exception {
		if (StringUtils.isBlank(userName))
			throw new ValidateException("user.userNameNull");
		if (StringUtils.isBlank(oldPassword))
			throw new ValidateException("user.oldPasswordNull");
		if (StringUtils.isBlank(password))
			throw new ValidateException("user.passwordNull");

		// 密码8位，并且带有字母数字和特殊符号
		/*if (!StringUtil.regex(oldPassword, PASSWORD_REGEX))
			throw new ValidateException("user.passwdNotRight");*/
		if (!StringUtil.regex(password, PASSWORD_REGEX))
			throw new ValidateException("user.passwordAlert");

		TUserApp user = null;
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userName", userName));
		List<?> userList = userCriteria.list();
		if (userList == null || userList.isEmpty()) {
			throw new ValidateException("user.userUnExist");
		} else {
			if (userList.size() != 1) {
				throw new ValidateException("common.illegalRequest");
			} else {
				user = (TUserApp) userList.get(0);
				if (!user.getPassword().equals(MD5Util.getMD5String(oldPassword).toLowerCase())) {
					throw new ValidateException("user.oldPasswordError");
				} else {
					user.setPassword(MD5Util.getMD5String(password).toLowerCase());
					updateEntity(user);
				}
			}
		}

		return user;
	}
	
	@Override
	public Object listConsoleUser(Pager pager, String keyWord) {
		Criteria criteria = getCriteria(TUser.class);
		criteria.add(Restrictions.ne("role", ""));
		criteria.add(Restrictions.isNotNull("role"));
		if (StringUtils.isNotBlank(keyWord)) {
			criteria.add(Restrictions.or(Restrictions.like("userName", "%" + keyWord + "%"),Restrictions.eq("userId", keyWord)));
		}
		criteria.addOrder(Order.desc("createTime"));

		return listPageQBCL(criteria, pager);
	}

	@Override
	public Object addConsoleUser(TUser user) throws Exception {
		if (StringUtils.isBlank(user.getUserName())) {
			throw new ValidateException("user.userNameNull");
		}
		if (StringUtils.isBlank(user.getPassword())) {
			throw new ValidateException("user.passwordNull");
		}
		if (StringUtils.isBlank(user.getRole())) {
			throw new ValidateException("user.roleNull");
		}
		if (StringUtils.isBlank(user.getBranch())) {
			throw new ValidateException("user.branchNull");
		}
		// 密码8位，并且带有字母数字和特殊符号
		// if (!StringUtil.regex(user.getPassword(), PASSWORD_REGEX))
		// throw new ValidateException("user.passwordAlert");
		Criteria userCriteria = getCriteria(TUser.class);
		userCriteria.add(Restrictions.eq("userName", user.getUserName()));
		List<?> userList = userCriteria.list();
		if (userList.size() > 0) {
			throw new ValidateException("user.userNameIsExist");
		}
		// 用户号
		String userId = CreateID.getID();
		user.setUserId(userId);
		// 设置用户密码
		user.setPassword(MD5Util.getMD5String(user.getPassword()).toLowerCase());
		// 默认可用
		user.setState(SysConstant.STATE_AVAILABLE);
		// 设置用户的时间
		user.setCreateTime(new Timestamp(new Date().getTime()));
		user.setLastTime(new Timestamp(new Date().getTime()));
		user.setLoginTime(new Timestamp(new Date().getTime()));
		
		//bing 20150802临时添加，因为页面添加的时候没有选择角色的地方,如果是Content user，默认权限为News user,Activity user
		if("Content user".equals(user.getRole())){
			user.setRole("News user,Activity user");
		}
		
		//user.setTcodes(null);
		// 保存用户信息
		if (saveEntity(user) == null)
			throw new ValidateException("common.sysException");

		return user;
	}

	@Override
	public TUser mergeLoginConsoleUser(String userName, String password,HttpSession session) throws Exception {
		if (StringUtils.isBlank(userName)) {
			throw new ValidateException("user.userNameNull");
		}
		if (StringUtils.isBlank(password)) {
			throw new ValidateException("user.passwordNull");
		}
		TUser user = null;
		Criteria userCriteria = getCriteria(TUser.class);
		userCriteria.add(Restrictions.eq("userName", userName));
		List<?> userList = userCriteria.list();
		if (!userList.isEmpty()) {
			if (userList.size() == 1) {
				TUser tUser = (TUser) userList.get(0);

				if (StringUtils.isBlank(tUser.getRole())) { // 如果用户没有角色的话，返回null
					return null;
				}
				if (password.equals(tUser.getPassword())) {
					if (tUser.getState() == SysConstant.STATE_AVAILABLE) {
						user = tUser;
						// 更新最后登录时间
						tUser.setLastTime(new Timestamp(new Date().getTime()));
						updateEntity(tUser);
					} else {
						throw new ValidateException("user.needActive");
					}
				} else {
					throw new ValidateException("user.passwdNotRight");
				}
			} else {
				throw new ValidateException("common.illegalRequest");
			}
		} else {
			throw new ValidateException("user.userUnExist");
		}
		return user;
	}

	@Override
	public Object countAllUser() throws Exception {
		HashMap<String, String> count_user = new HashMap<String, String>();
		// 统计总的App的总人数
		Criteria criteria = getCriteria(TUser.class);
		criteria.add(Restrictions.ne("role", ""));
		criteria.add(Restrictions.isNotNull("role"));
		criteria.setProjection(Projections.rowCount());
		List<?> userCountList = criteria.list();
		count_user.put("Users count", userCountList.get(0).toString());

		// 统计type为locked的人数
		Criteria criteria_lock = getCriteria(TUser.class);
		criteria_lock.add(Restrictions.ne("role", ""));
		criteria_lock.add(Restrictions.isNotNull("role"));
		criteria_lock.add(Restrictions.eq("state", SysConstant.STATE_IS_LOCKED));
		criteria_lock.setProjection(Projections.rowCount());
		List<?> userLockCountList = criteria_lock.list();
		count_user.put("Locked count", userLockCountList.get(0).toString());

		return count_user;
	}

	@Override
	public Object getConsoleUser(String userId) throws Exception {
		TUser tUser = null;
		if (StringUtils.isNotBlank(userId)) {
			tUser = findEntity(TUser.class, userId);
			if (tUser != null) {
				return tUser;
			} else {
				throw new ValidateException("user.userUnExist");
			}
		}
		return new TUser();
	}

	@Override
	public Object getNewUserPassword() throws Exception {
		String newpassword = "";
		for (int i = 0; i < 8; i++) {
			newpassword = newpassword + ((int) (Math.random() * 10) % 9 + 1);
		}
		HashMap<String, String> newHashMap = new HashMap<String, String>();

		newHashMap.put("newpasswrod", newpassword);

		return newHashMap;
	}

	@Override
	public Object editConsoleUser(TUser user) throws Exception {
		if (StringUtils.isBlank(user.getRole())) {
			throw new ValidateException("user.roleNull");
		}
		TUser tUser = null;
		if (user != null && StringUtils.isNotBlank(user.getUserId())) {
			tUser = findEntity(TUser.class, user.getUserId());
			if (tUser != null) {

				if (StringUtils.isNotBlank(user.getPassword())) {
					tUser.setPassword(user.getPassword());
				}
				if (StringUtils.isNotBlank(user.getRole())) {
					tUser.setRole(user.getRole());
				}
				if (StringUtils.isNotBlank(user.getUserType())) {
					tUser.setUserType(user.getUserType());
				}
				if (StringUtils.isNotBlank(user.getBranch())) {
					tUser.setBranch(user.getBranch());
				}
				updateEntity(tUser);
			}
		}
		if (tUser != null) {
			return tUser;
		} else {
			throw new ValidateException("user.userUnExist");
		}
	}

	@Override
	public Object editUserState(String userId, int state) throws Exception {
		TUser tUser = null;
		if (StringUtils.isNotBlank(userId)) {
			tUser = findEntity(TUser.class, userId);
			if (tUser != null) {
				tUser.setLastTime(new Timestamp(new Date().getTime()));
				tUser.setState(state);
				updateEntity(tUser);
			}
		}
		if (tUser != null) {
			return tUser;
		} else {
			throw new ValidateException("user.userUnExist");
		}
	}
	
	
	/**
	 * APP用户激活
	 * 需要前端传过来用户信息及扫描二维码获得数据
	 * 将传过来的二维码与staffId加密后进行对比，如果结果一致，则添加该用户到数据库，反之不能添加该用户
	 * @return Object
	 * @throws Exception
	 * @author Bing  2014-11-14 19:49
	 */
	@Override
	public Object activeUserByCompareCode(TUserApp userApp, String staffId,String code,String udid)
			throws Exception {
		//1.将staffId加密后与code对比
		String encrypt_StaffId = encryptString(staffId);//加密
		if(!code.equals(encrypt_StaffId)){
			throw new ValidateException("user.codeInvalid");
		}
		//2、判断用户名是否为空
		if (StringUtils.isBlank(userApp.getUserName())){
			throw new ValidateException("user.userNameNull");
		}
		//3、判断密码是否符合要求
		if (!StringUtil.regex(userApp.getPassword(), PASSWORD_REGEX)){
			throw new ValidateException("user.passwordAlert");
		}	
		//4、判断用户名是否存在
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userName", userApp.getUserName()));
		List<?> userList = userCriteria.list();
		if (userList.size() > 0) {
			throw new ValidateException("user.userNameIsExist");
		}
		//5、判断用户设备编号是否为空
		if (StringUtils.isBlank(udid)) {
			throw new ValidateException("user.udidisnull");
		}
		
		//6、添加用户   注意用户状态是激活状态
		
		/***** 用户号 ****/
		String userId = CreateID.getID();
		userApp.setUserId(userId);
		
		/***** 密码 ****/
		userApp.setPassword(MD5Util.getMD5String(userApp.getPassword()).toLowerCase());

		/***** 设置用户的udid值 ****/
		userApp.setUserUDID(udid);
		
		/***** 设置用户类型 ****/
		//userApp.setUserType("app user");
		
		/***** 默认已经激活可用  ****/
		userApp.setState(SysConstant.STATE_AVAILABLE);

		/***** 设置用户的时间  ****/
		userApp.setCreateTime(new Timestamp(new Date().getTime()));

		userApp.setLastTime(new Timestamp(new Date().getTime()));

		userApp.setLoginTime(new Timestamp(new Date().getTime()));


		/***** 保存用户信息  ****/
		if (saveEntity(userApp) == null) {
				throw new ValidateException("common.sysException");
		}
		
		return userApp;
	}
	
	
	/**
	 * 临时加密算法
	 * @param str
	 * @return
	 */
	public String encryptString(String str){
		String encryptStr = str + "a";
		return encryptStr;
	}
	public  Object getObjectById(Class<?> cls,String id) throws Exception {
		return findEntity(cls, id);
	}
	
	/**
	 * 激活二维码
	 * @author Bing  2014-11-21
	 */
	@Override
	public Object activeQRCode(String code,String udid) throws Exception {
		if (StringUtils.isBlank(code)) {
			throw new ValidateException("user.infoNotRight");
		}
		//modified by william 2014-11-30
		TUserApp user = new TUserApp();
		String staffId = null;
		String userName = null;
		String english_name = null;
		String chinese_name = null;
		String phone = "";
		String entity = null;
		String department = null;
		String email = null;
		String actionType = null;
		List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
		try {
			String[] coderInfos = null;
			if(code.contains(",")){
				//coderInfos = code.split(",");
			}else{
				coderInfos = NewUserSignUpQRCoder.decrypt(code,AppConstants.QR_CODER_AES_STATIC_KEY);
			}
			if (coderInfos != null && coderInfos.length == 6) {
				staffId = coderInfos[0];
				entity = coderInfos[1];
				department = coderInfos[2];
				email = coderInfos[3];
				chinese_name = coderInfos[4];
				actionType = coderInfos[5];
				if (!AppConstants.ACTIONTYPE_NEWUSERSIGNUP.equals(actionType)) {
					throw new ValidateException("user.infoNotRight");
				}
				Map<String, String> map = new HashMap<String, String>();
				//
				if(email.contains("@")){
					userName = email.substring(0,email.indexOf("@"));
					english_name = userName.replace(".", " ");
					userName = userName.replace(".", "").replace(" ", "");
				}else if(email.contains("/")){
					userName = email.substring(0,email.indexOf("/"));
					english_name = userName.replace(".", " ");
					userName = userName.replace(".", "").replace(" ", "");
				}else{
					userName = email;
					english_name = userName.replace(".", " ");
				}

				map.put("staffId", staffId);
				map.put("english_name", english_name);
				map.put("chinese_name", chinese_name);
				map.put("phone", phone);
				map.put("userName", userName);
				map.put("email", email);
				map.put("branch", entity);
				map.put("position", department);
				rsList.add(map);
			} else {
				throw new ValidateException("user.infoNotRight");
			}
		} catch (Exception e) {
			throw new ValidateException("user.infoNotRight");
		}
		
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userId", staffId));
		List<?> userList = userCriteria.list();
		if (userList != null&&userList.size()>0) {
			if(userList.size()>1){
				throw new ValidateException("user.multiple");
			}
			TUserApp oldUser = (TUserApp)userList.get(0);
			if(oldUser.getState().equals(SysConstant.STATE_AVAILABLE)){
				throw new ValidateException("user.haveActivated");
			}
			//判断用户名重复
			Criteria usercri = getCriteria(TUserApp.class);
			usercri.add(Restrictions.not(Restrictions.eq("userId", staffId)));
			usercri.add(Restrictions.eq("userName", userName));
			if(usercri.list()!=null){
				if(usercri.list().size()>0){
					userName = ""+Calendar.getInstance().getTimeInMillis();
					//throw new ValidateException("user.userNameIsExist");
				}
			}
			user.setUserId(staffId);
			user.setUserName(userName);
			user.setStaffId(staffId);
			user.setEnglish_name(english_name);
			user.setChinese_name(chinese_name);
			user.setPhone(phone);
			user.setEmail(email);
			user.setBranch(entity);
			user.setPosition(department);
			user.setUserUDID(udid);
			/***** 默认已经激活不可用 ****/
			user.setState(SysConstant.STATE_NOT_AVAILABLE);

			/***** 设置用户的时间 ****/
			user.setCreateTime(new Timestamp(new Date().getTime()));

			user.setLastTime(new Timestamp(new Date().getTime()));

			user.setLoginTime(new Timestamp(new Date().getTime()));
			
			user.setPassword(oldUser.getPassword());
			user.setUserUDID(oldUser.getUserUDID());
			updateObj(user);
			if (user != null) {
				return rsList;
			}
		}else{
			//判断用户名重复
			Criteria usercri = getCriteria(TUserApp.class);
			usercri.add(Restrictions.eq("userName", userName));
			if(usercri.list()!=null){
				if(usercri.list().size()>0){
					userName = ""+Calendar.getInstance().getTimeInMillis();
					//throw new ValidateException("user.userNameIsExist");
				}
			}
			
			
			user.setUserId(staffId);
			user.setUserName(userName);
			user.setStaffId(staffId);
			user.setEnglish_name(english_name);
			user.setChinese_name(chinese_name);
			user.setPhone(phone);
			user.setEmail(email);
			user.setBranch(entity);
			user.setPosition(department);
			user.setUserUDID(udid);
			/***** 默认已经激活可用 ****/
			user.setState(SysConstant.STATE_NOT_AVAILABLE);

			/***** 设置用户的时间 ****/
			user.setCreateTime(new Timestamp(new Date().getTime()));

			user.setLastTime(new Timestamp(new Date().getTime()));

			user.setLoginTime(new Timestamp(new Date().getTime()));

			/***** 保存用户信息 ****/
			if (saveEntity(user) == null) {
				throw new ValidateException("common.sysException");
			}
		}
		return rsList;
	}
	/**
	 * 激活二维码
	 * @author Bing  2014-11-21
	 */
//	@Override
//	public Object activeQRCode(String code,String udid) throws Exception {
//		if (StringUtils.isBlank(code)) {
//			throw new ValidateException("user.infoNotRight");
//		}
//		//modified by william 2014-11-30
//		TUserApp user = new TUserApp();
//		String staffId = null;
//		String userName = null;
//		String english_name = null;
//		String chinese_name = null;
//		String phone = "";
//		String entity = null;
//		String department = null;
//		String email = null;
//		String actionType = null;
//		List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
//		try {
//			String[] coderInfos = null;
//			if(code.contains(",")){
//				//coderInfos = code.split(",");
//			}else{
//				coderInfos = NewUserSignUpQRCoder.decrypt(code,AppConstants.QR_CODER_AES_STATIC_KEY);
//			}
//			if (coderInfos != null && coderInfos.length == 6) {
//				staffId = coderInfos[0];
//				entity = coderInfos[1];
//				department = coderInfos[2];
//				email = coderInfos[3];
//				chinese_name = coderInfos[4];
//				actionType = coderInfos[5];
//				if (!AppConstants.ACTIONTYPE_NEWUSERSIGNUP.equals(actionType)) {
//					throw new ValidateException("user.infoNotRight");
//				}
//				Map<String, String> map = new HashMap<String, String>();
//				//
//				if(email.contains("@")){
//					userName = email.substring(0,email.indexOf("@"));
//					english_name = userName.replace(".", " ");
//					userName = userName.replace(".", "").replace(" ", "");
//				}else if(email.contains("/")){
//					userName = email.substring(0,email.indexOf("/"));
//					english_name = userName.replace(".", " ");
//					userName = userName.replace(".", "").replace(" ", "");
//				}else{
//					userName = email;
//					english_name = userName.replace(".", " ");
//				}
//
//				map.put("staffId", staffId);
//				map.put("english_name", english_name);
//				map.put("chinese_name", chinese_name);
//				map.put("phone", phone);
//				map.put("userName", userName);
//				map.put("email", email);
//				map.put("branch", entity);
//				map.put("position", department);
//				rsList.add(map);
//			} else {
//				throw new ValidateException("user.infoNotRight");
//			}
//		} catch (Exception e) {
//			throw new ValidateException("user.infoNotRight");
//		}
//		//判断用户名重复
//		Criteria usercri = getCriteria(TUserApp.class);
//		usercri.add(Restrictions.not(Restrictions.eq("userId", staffId)));
//		usercri.add(Restrictions.eq("userName", userName));
//		if(usercri.list()!=null){
//			if(usercri.list().size()>0){
//				userName = ""+Calendar.getInstance().getTimeInMillis();
//			}
//		}
//		
//		
//		user.setUserId(staffId);
//		user.setUserName(userName);
//		user.setStaffId(staffId);
//		user.setEnglish_name(english_name);
//		user.setChinese_name(chinese_name);
//		user.setPhone(phone);
//		user.setEmail(email);
//		user.setBranch(entity);
//		user.setPosition(department);
//		/***** 默认已经激活不可用 ****/
//		user.setState(SysConstant.STATE_NOT_AVAILABLE);
//
//		/***** 设置用户的时间 ****/
//		user.setCreateTime(new Timestamp(new Date().getTime()));
//		user.setLastTime(new Timestamp(new Date().getTime()));
//		user.setLoginTime(new Timestamp(new Date().getTime()));
//		
//		
//		Criteria userCriteria = getCriteria(TUserApp.class);
//		userCriteria.add(Restrictions.eq("userUDID", udid));
//		List<?> userList = userCriteria.list();
//		if (userList != null&&userList.size()>0) {
//			if(userList.size()>1){
//				throw new ValidateException("user.multiple");
//			}
//			TUserApp oldUser = (TUserApp)userList.get(0);
//			if(oldUser.getState()!=null&&!"".equals(oldUser.getState())){
//				if(oldUser.getState().equals(SysConstant.STATE_AVAILABLE)){
//					throw new ValidateException("user.haveActivated");
//				}
//			}
//			
//			user.setUserUDID(oldUser.getUserUDID());
//			user.setDevice_type(oldUser.getDevice_type());
//			user.setPush_id(oldUser.getPush_id());
//			if(deleteEntity(oldUser)){
//				saveOrUpdateEntity(user);
//				return rsList;
//			}else{
//				throw new ValidateException("golbal.error");
//			}
//		}else{
//			saveOrUpdateEntity(user);
//		}
//		return rsList;
//	}
	/**
	 * check UserName Sensitive Wording
	 * @author william wu 2014-12-15
	 * @param userName
	 * @return
	 */
	private boolean checkUserNameSensitiveWording(String userName){
		String[] names = new String[]{"HSBC","GLTC","HSDC","HDPG","GSC","GZH","GR","HTS","HTSA","HR","Admin","Finance","汇丰","匯豐","汇软","匯軟","徐养福","欧智华","徐養福","歐智華","范智廉","範智廉","黄碧娟","黃碧娟","王冬胜","王冬勝","施穎茵","施颖茵","郑小康","鄭小康","史美伦","史美倫","冯国纶","馮國綸","麦荣恩","麥榮恩"};
		for (int i = 0; i < names.length; i++) {
			if(userName.toUpperCase().contains(names[i].toUpperCase())){
				return false;
			}
		}
		return true;
	}

	@Override
	public TUserApp activeSetPassword(String staffId,String userName,String password,String udid)
			throws Exception {
		if (StringUtils.isBlank(staffId))
			throw new ValidateException("user.userNull");
		
		if (StringUtils.isBlank(password))
			throw new ValidateException("user.passwordNull");

		if (StringUtils.isBlank(udid)) {
			throw new ValidateException("user.udidisnull");
		}
		//add by william 2014-12-15
		if (!StringUtil.regex(userName, USERNAME_REGEX))
			throw new ValidateException("user.userNameAlert");
		if (!this.checkUserNameSensitiveWording(userName))
			throw new ValidateException("user.userNameIsExist");
		// 密码8位，并且带有字母数字
		if (!StringUtil.regex(password, PASSWORD_REGEX))
			throw new ValidateException("user.passwordAlert");

		TUserApp user = null;
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userId", staffId));
		List<?> userList = userCriteria.list();
		if (userList == null || userList.isEmpty()) {
			throw new ValidateException("user.userUnExist");
		} else {
			if (userList.size() != 1) {
				//throw new ValidateException("common.illegalRequest");
				throw new ValidateException("user.multiple");
			} else {
				//判断用户名重复
				Criteria usercri = getCriteria(TUserApp.class);
				usercri.add(Restrictions.not(Restrictions.eq("userId", staffId)));
				usercri.add(Restrictions.eq("userName", userName));
				if(usercri.list()!=null){
					if(usercri.list().size()>0){
						throw new ValidateException("user.userNameIsExist");
					}
				}
				user = (TUserApp) userList.get(0);
				user.setState(SysConstant.STATE_AVAILABLE);
				user.setUserUDID(udid);
				user.setUserName(userName);
				user.setPassword(MD5Util.getMD5String(password).toLowerCase());
				updateEntity(user);
			}
		}

		return user;
	}
	
	/**
	 * forget password QR code
	 * @author William  2014-12-08
	 */
	@SuppressWarnings("unused")
	@Override
	public Object forgetPasswordQRCode(String code) throws Exception {
		if (StringUtils.isBlank(code)) {
			throw new ValidateException("user.codeUnknow");
		}

		List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		
		String staffId = null;
		String chinese_name = null;
		String entity = null;
		String department = null;
		String email = null;
		String actionType = null;
		try {
			String[] coderInfos = null;
			coderInfos = NewUserSignUpQRCoder.decrypt(code,AppConstants.QR_CODER_AES_STATIC_KEY);
			if (coderInfos != null && coderInfos.length == 6) {
				staffId = coderInfos[0];
				entity = coderInfos[1];
				department = coderInfos[2];
				email = coderInfos[3];
				chinese_name = coderInfos[4];
				actionType = coderInfos[5];
				if (!AppConstants.ACTIONTYPE_FORGETAPPPASSWORD.equals(actionType)) {
					throw new ValidateException("user.infoNotRight");
				}
			} else {
				throw new ValidateException("user.infoNotRight");
			}
		} catch (Exception e) {
			throw new ValidateException("user.infoNotRight");
		}
		
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userId", staffId));
		List<?> userList = userCriteria.list();
		if (userList != null&&userList.size()>0) {
			TUserApp user =  (TUserApp)userList.get(0);
			if(!user.getState().equals(SysConstant.STATE_AVAILABLE)){
				throw new ValidateException("user.needActive");
			}
			map.put("staffId", user.getUserId());
			map.put("userName", user.getUserName());
			rsList.add(map);
		}else{
			throw new ValidateException("user.userNull");
		}
		return rsList;
	}
	

	/**
	 * forget set password
	 * @author William  2014-12-08
	 */
	@Override
	public TUserApp activeForgetSetPassword(String staffId,String password)
			throws Exception {
		if (StringUtils.isBlank(staffId))
			throw new ValidateException("user.userNull");
		
		if (StringUtils.isBlank(password))
			throw new ValidateException("user.passwordNull");
		/*
		if (StringUtils.isBlank(udid)) {
			throw new ValidateException("user.udidisnull");
		}*/
		// 密码8位，并且带有字母数字和特殊符号
		if (!StringUtil.regex(password, PASSWORD_REGEX))
			throw new ValidateException("user.passwordAlert");

		TUserApp user = null;
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userId", staffId));
		List<?> userList = userCriteria.list();
		if (userList == null || userList.isEmpty()) {
			throw new ValidateException("user.userUnExist");
		} else {
			if (userList.size() != 1) {
				throw new ValidateException("common.illegalRequest");
			} else {
				user = (TUserApp) userList.get(0);
				if(!user.getState().equals(SysConstant.STATE_AVAILABLE)){
					throw new ValidateException("user.needActive");
				}
				user.setPassword(MD5Util.getMD5String(password).toLowerCase());
				updateEntity(user);
			}
		}

		return user;
	}

	
	/**
	 * change device QR code
	 * @author William  2014-12-08
	 */
	@SuppressWarnings("unused")
	@Override
	public Object activeChangeDeviceQRCode(String code,String udid) throws Exception {
		if (StringUtils.isBlank(code)) {
			throw new ValidateException("user.codeUnknow");
		}

		List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		
		String staffId = null;
		String chinese_name = null;
		String entity = null;
		String department = null;
		String email = null;
		String actionType = null;
		try {
			String[] coderInfos = null;
			coderInfos = NewUserSignUpQRCoder.decrypt(code,AppConstants.QR_CODER_AES_STATIC_KEY);
			if (coderInfos != null && coderInfos.length == 6) {
				staffId = coderInfos[0];
				entity = coderInfos[1];
				department = coderInfos[2];
				email = coderInfos[3];
				chinese_name = coderInfos[4];
				actionType = coderInfos[5];
				if (!AppConstants.ACTIONTYPE_DEVICECHANGE.equals(actionType)) {
					throw new ValidateException("user.infoNotRight");
				}
			} else {
				throw new ValidateException("user.infoNotRight");
			}
		} catch (Exception e) {
			throw new ValidateException("user.infoNotRight");
		}
		
		Criteria userCriteria = getCriteria(TUserApp.class);
		userCriteria.add(Restrictions.eq("userId", staffId));
		List<?> userList = userCriteria.list();
		if (userList != null&&userList.size()>0) {
			TUserApp user =  (TUserApp)userList.get(0);
			if(!user.getState().equals(SysConstant.STATE_AVAILABLE)){
				throw new ValidateException("user.needActive");
			}
			if(udid!=null&&!udid.equals("")){
				user.setUserUDID(udid);
				saveEntity(user);
			}
			map.put("staffId", user.getUserId());
			map.put("userName", user.getUserName());
			rsList.add(map);
		}else{
			throw new ValidateException("user.userNull");
		}
		return rsList;
	}
//	/**
//	 *  设置推送信息，push_id    device_type   udid
//	 * @author Dave  2015-7-02
//	 */
//	@Override
//	public String setPushInfo(String udid, String push_id, String device_type) throws Exception {
		// TODO Auto-generated method stub
//		if("".equals(udid)||udid==null){
//			throw new ValidateException("golbal.error");
//		}
//		if("".equals(push_id)||push_id==null){
//			throw new ValidateException("golbal.error");
//		}
//		if("".equals(device_type)||device_type==null){
//			throw new ValidateException("golbal.error");
//		}
//		Criteria userCriteria = getCriteria(TUserApp.class);
//		userCriteria.add(Restrictions.eq("userUDID", udid));
//		@SuppressWarnings("unchecked")
//		List<TUserApp> userList = userCriteria.list();
//		TUserApp userApp=new TUserApp();
//		if (userList != null&&userList.size()>0) {
//			userApp=userList.get(0);
//			if(userApp!=null){
//				if(udid.equals(userApp.getUserUDID())&&push_id.equals(userApp.getPush_id())&&device_type.equals(userApp.getDevice_type())){
//					return "true";
//				}else{
//					//当同一个udid的其他信息不同时将更新当前传送的信息
//					userApp.setUserUDID(udid);
//					userApp.setPush_id(push_id);
//					userApp.setDevice_type(device_type);
//					updateEntity(userApp);
//					return "true";
//				}
//			}
//		}else{
//			//可能存在重新安装应用（udid不同，但百度给的userId是相同）
//			Criteria criteria = getCriteria(TUserApp.class);
//			criteria.add(Restrictions.eq("userUDID", udid));
//			criteria.add(Restrictions.eq("push_id", push_id));
//			@SuppressWarnings("unchecked")
//			List<TUserApp> user_list = userCriteria.list();
//			if (user_list != null&&user_list.size()>0) {
//				for(TUserApp u:user_list){
//					deleteEntity(u);
//				}
//			}
//			
//			
//			userApp.setUserId(CreateID.getID());
//			userApp.setUserUDID(udid);
//			userApp.setPush_id(push_id);
//			userApp.setDevice_type(device_type);
//			saveEntity(userApp);
//		}
//		return "true";
//	}
	
	/**
	 * 设置用户的百度推送相关信息
	 */
	@Override
	public String setPushInfo(String udid,String channelId,String baiduUserId,String device_type) throws Exception {

		if("".equals(udid)||udid==null){
			throw new ValidateException("golbal.error");
		}
//		if("".equals(channelId)||channelId==null){
//			throw new ValidateException("golbal.error");
//		}
		if("".equals(device_type)||device_type==null){
			throw new ValidateException("golbal.error");
		}
//		if(!"ios".equals(device_type)){
//			if("".equals(baiduUserId)||baiduUserId==null){
//				throw new ValidateException("golbal.error");
//			}
//		}
		
		TStaffpushinfo push = this.findEntity(TStaffpushinfo.class, udid);
		if(push==null){
			push = new TStaffpushinfo();
			push.setUdid(udid);
			push.setChannelId(channelId);
			push.setUserId(baiduUserId);
			push.setDevice_type(device_type);
			Timestamp t = new Timestamp(new Date().getTime());
			push.setAddtime(t);
			push.setUsername("");
			
			//保存
			if (saveEntity(push) == null) {
				throw new ValidateException("common.illegalRequest");
			}
		}
		return "true";
	}
}
